package com.itheima.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.take_delivery.Promotion;
import com.itheima.bos.service.take_delivery.PromotionService;
import com.itheima.bos.web.action.common.BaseAction;

/*
 * 宣传活动的管理
 */

@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class PromotionAction extends BaseAction<Promotion> {

	@Autowired
	private PromotionService promotionService;

	/*
	 * 保存宣传活动的方法
	 */
	private File titleImgFile;

	private String titleImgFileFileName;

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	@Action(value = "promotion_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/take_delivery/promotion.html") })
	public String save() {

		// 宣传图的路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload");
		String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";

		System.out.println(savePath);
		System.out.println(saveUrl);

		// 产生随机数拼装文件名
		UUID uuid = UUID.randomUUID();
		String randomFileName = uuid + titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));

		try {
			FileUtils.copyFile(titleImgFile, new File(savePath, randomFileName));
		} catch (IOException e) {

			e.printStackTrace();
		}

		System.out.println(saveUrl + randomFileName);

		model.setTitleImg(saveUrl + randomFileName);
		promotionService.save(model);
		return SUCCESS;
	}

	/*
	 * 查询宣传活动的方法
	 */
	@Action(value = "promotion_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		
		Pageable pageable = new PageRequest(page-1,rows);
		
		Page<Promotion> pageData = promotionService.findPageData(pageable);
		
		pushPageDataToValueStack(pageData);
		
		return SUCCESS;
	}
}
